// 全局变量
let candleData = [];
let klineCache = {};
let myChart = null; // K线图实例变量
let currentKlineData = []; // 存储当前K线数据
let currentSymbol = ''; // 当前显示的交易对
let currentInterval = ''; // 当前显示的时间间隔

// 更新进度显示
function updateProgress(text) {
    const progressElement = document.querySelector('.loading-progress');
    if (progressElement) {
        progressElement.textContent = text;
    }
}

document.addEventListener('DOMContentLoaded', function() {
    // 初始化事件监听
    document.getElementById('getData').addEventListener('click', fetchAndAnalyzeData);
    
    // 监听时间范围选择变化，在切换时控制K线图显示
    document.getElementById('timeRange').addEventListener('change', function() {
        const timeRange = this.value;
        // 如果不是今天，立即隐藏K线图
        if (timeRange !== 'today') {
            document.getElementById('klineContainer').style.display = 'none';
        }
    });
    
    // 自动执行一次数据获取
    fetchAndAnalyzeData();
});

// 获取指定时间范围的开始时间戳
function getStartTimestamp(range) {
    const now = new Date();
    console.log('当前系统时间:', now.toLocaleString());
    
    let result;
    switch (range.toLowerCase()) {
        case 'today':
            // 今天凌晨0点
            now.setHours(0, 0, 0, 0);
            result = now.getTime();
            break;
        case 'yesterday':
            // 昨天凌晨0点
            const yesterday = new Date();
            yesterday.setDate(yesterday.getDate() - 1);
            yesterday.setHours(0, 0, 0, 0);
            result = yesterday.getTime();
            break;
        case '1w':
            now.setDate(now.getDate() - 7);
            now.setHours(0, 0, 0, 0);
            result = now.getTime();
            break;
        case '1m':
            now.setMonth(now.getMonth() - 1);
            now.setHours(0, 0, 0, 0);
            result = now.getTime();
            break;
        case '3m':
            now.setMonth(now.getMonth() - 3);
            now.setHours(0, 0, 0, 0);
            result = now.getTime();
            break;
        case '6m':
            now.setMonth(now.getMonth() - 6);
            now.setHours(0, 0, 0, 0);
            result = now.getTime();
            break;
        case '1y':
            now.setFullYear(now.getFullYear() - 1);
            now.setHours(0, 0, 0, 0);
            result = now.getTime();
            break;
        case '2y':
            now.setFullYear(now.getFullYear() - 2);
            now.setHours(0, 0, 0, 0);
            result = now.getTime();
            break;
        case '3y':
            now.setFullYear(now.getFullYear() - 3);
            now.setHours(0, 0, 0, 0);
            result = now.getTime();
            break;
        case '4y':
            now.setFullYear(now.getFullYear() - 4);
            now.setHours(0, 0, 0, 0);
            result = now.getTime();
            break;
        case '5y':
            now.setFullYear(now.getFullYear() - 5);
            now.setHours(0, 0, 0, 0);
            result = now.getTime();
            break;
        case '6y':
            now.setFullYear(now.getFullYear() - 6);
            now.setHours(0, 0, 0, 0);
            result = now.getTime();
            break;
        case '7y':
            now.setFullYear(now.getFullYear() - 7);
            now.setHours(0, 0, 0, 0);
            result = now.getTime();
            break;
        default:
            // 默认今天
            now.setHours(0, 0, 0, 0);
            result = now.getTime();
            break;
    }
    return result;
}

// 获取结束时间戳
function getEndTimestamp(range) {
    const now = new Date();
    let result;
    
    switch (range.toLowerCase()) {
        case 'yesterday':
            // 今天凌晨0点
            const today = new Date();
            today.setHours(0, 0, 0, 0);
            result = today.getTime() - 1; // 减去1毫秒，确保不包含今天的数据
            break;
        default:
            // 当前时间
            result = now.getTime();
            break;
    }
    return result;
}

// 获取K线数据
async function fetchKlineData(symbol, interval, startTime, endTime, range) {
    try {
        console.log(`正在获取${interval}周期数据 - 范围: ${new Date(startTime).toLocaleString()} 至 ${new Date(endTime).toLocaleString()}, 范围类型: ${range}`);
            
        // 通过API获取数据，添加range参数
        const response = await fetch(`/api/history?symbol=${symbol}&interval=${interval}&startTime=${startTime}&endTime=${endTime}&range=${range}`);
            
        if (!response.ok) {
            throw new Error(`获取K线数据失败: ${response.status}`);
        }
        
        const data = await response.json();
        console.log(`成功获取 ${data.length} 条K线数据`);
        
        // 转换数据格式
        return data.map(kline => ({
            time: parseInt(kline[0]),
            open: parseFloat(kline[1]),
            high: parseFloat(kline[2]),
            low: parseFloat(kline[3]),
            close: parseFloat(kline[4]),
            volume: parseFloat(kline[5])
        }));
    } catch (error) {
        console.error('获取K线数据出错:', error);
        throw error;
    }
}

// 分析K线数据
function analyzeData(data) {
    if (!data || data.length === 0) {
        return {
            total: 0,
            upCount: 0,
            downCount: 0,
            flatCount: 0,
            upPercent: 0,
            downPercent: 0,
            flatPercent: 0,
            continuousUpCounts: {},
            continuousDownCounts: {}
        };
    }
    
    let upCount = 0;
    let downCount = 0;
    let flatCount = 0;
    
    // 简单统计涨跌平
    for (const kline of data) {
        if (kline.close > kline.open) {
            upCount++;
        } else if (kline.close < kline.open) {
            downCount++;
        } else {
            flatCount++;
        }
    }
    
    // 计算百分比
    const total = data.length;
    const upPercent = total > 0 ? (upCount / total * 100).toFixed(2) : 0;
    const downPercent = total > 0 ? (downCount / total * 100).toFixed(2) : 0;
    const flatPercent = total > 0 ? (flatCount / total * 100).toFixed(2) : 0;
    
    // 分析连续上涨和下跌
    const { continuousUpCounts, continuousDownCounts } = analyzeConsecutiveKlines(data);
    
    return {
        total,
        upCount,
        downCount,
        flatCount,
        upPercent,
        downPercent,
        flatPercent,
        continuousUpCounts,
        continuousDownCounts
    };
}

// 分析连续K线
function analyzeConsecutiveKlines(data) {
    const continuousUpCounts = {};
    const continuousDownCounts = {};
    
    // 初始化计数器
    let currentUpCount = 0;
    let currentDownCount = 0;
    
    for (let i = 0; i < data.length; i++) {
        const kline = data[i];
        const isUp = kline.close > kline.open;
        const isDown = kline.close < kline.open;
        
        // 处理上涨
        if (isUp) {
            currentUpCount++;
            
            // 如果下跌计数大于0，记录并重置
            if (currentDownCount > 0) {
                continuousDownCounts[currentDownCount] = (continuousDownCounts[currentDownCount] || 0) + 1;
                currentDownCount = 0;
            }
        }
        // 处理下跌
        else if (isDown) {
            currentDownCount++;
            
            // 如果上涨计数大于0，记录并重置
            if (currentUpCount > 0) {
                continuousUpCounts[currentUpCount] = (continuousUpCounts[currentUpCount] || 0) + 1;
                currentUpCount = 0;
            }
        }
        // 处理平盘
        else {
            // 平盘会中断连续性
            if (currentUpCount > 0) {
                continuousUpCounts[currentUpCount] = (continuousUpCounts[currentUpCount] || 0) + 1;
                currentUpCount = 0;
            }
            
            if (currentDownCount > 0) {
                continuousDownCounts[currentDownCount] = (continuousDownCounts[currentDownCount] || 0) + 1;
                currentDownCount = 0;
            }
        }
    }
    
    // 处理最后一组
    if (currentUpCount > 0) {
        continuousUpCounts[currentUpCount] = (continuousUpCounts[currentUpCount] || 0) + 1;
    }
    
    if (currentDownCount > 0) {
        continuousDownCounts[currentDownCount] = (continuousDownCounts[currentDownCount] || 0) + 1;
    }
    
    return { continuousUpCounts, continuousDownCounts };
}

// 更新UI
function updateUI(analysis) {
    // 更新基础统计数据
    document.getElementById('totalCandles').textContent = analysis.total;
    document.getElementById('upCandles').textContent = `${analysis.upCount} (${analysis.upPercent}%)`;
    document.getElementById('downCandles').textContent = `${analysis.downCount} (${analysis.downPercent}%)`;
    document.getElementById('flatCandles').textContent = `${analysis.flatCount} (${analysis.flatPercent}%)`;
    
    // 更新连续上涨和下跌统计表格
    updateStatsTable('upStatsTable', analysis.continuousUpCounts, analysis.total);
    updateStatsTable('downStatsTable', analysis.continuousDownCounts, analysis.total);
}

// 更新统计表格
function updateStatsTable(tableId, data, total) {
    const table = document.getElementById(tableId);
    table.innerHTML = '';
    
    // 获取所有连续次数，并按次数排序
    const counts = Object.keys(data).map(Number).sort((a, b) => a - b);
    
    for (const count of counts) {
        if (count >= 2) { // 只显示连续2次及以上的
            const occurrences = data[count];
            
            const row = document.createElement('tr');
            
            // 连续次数
            const countCell = document.createElement('td');
            countCell.textContent = count + '次';
            row.appendChild(countCell);
            
            // 出现次数
            const occurrencesCell = document.createElement('td');
            occurrencesCell.textContent = occurrences;
            row.appendChild(occurrencesCell);
            
            table.appendChild(row);
        }
    }

    // 如果没有数据，显示空行
    if (counts.length === 0 || !counts.some(count => count >= 2)) {
        const row = document.createElement('tr');
        const cell = document.createElement('td');
        cell.colSpan = 2;
        cell.textContent = '无连续数据';
        cell.style.textAlign = 'center';
        row.appendChild(cell);
        table.appendChild(row);
    }
}
    
// 显示K线图
function showKlineChart(data, symbol, interval) {
    const container = document.getElementById('klineContainer');
    container.style.display = 'block';
    
    document.getElementById('kline-title').textContent = `${symbol} ${interval} 今天K线图`;
            
    // 创建K线图
    if (myChart) {
        myChart.dispose();
    }
    
    myChart = echarts.init(document.getElementById('kline-chart'));
    
    // 对数据进行排序，确保按时间顺序
    data.sort((a, b) => a.time - b.time);
    
    // 打印第一条原始数据用于调试
    console.log('原始K线数据第一条:', data[0]);
    
    // 准备K线数据
    const klineData = data.map(item => [
        // ECharts的K线图要求数据格式为 [open, close, lowest, highest]
        item.open,      // 开盘价
        item.close,     // 收盘价
        item.low,       // 最低价
        item.high,      // 最高价
    ]);
    
    // 准备时间轴数据
    const timeData = data.map(item => formatDate(new Date(item.time)));
    
    // 打印处理后的数据用于调试
    console.log('处理后的第一条K线数据:', klineData[0]);
    console.log('对应的时间:', timeData[0]);

    // 计算默认显示区域 - 当有数据时自动显示最新的20条数据
    let startPercent = 0;
    let endPercent = 100;
    
    if (data.length > 20) {
        // 计算最后20条数据在整个数据集中的比例
        startPercent = Math.max(0, 100 - (20 / data.length * 100));
        endPercent = 100;
        console.log(`数据总数 ${data.length} 条，默认显示最新的20条，缩放比例: ${startPercent}% - ${endPercent}%`);
    }

    // 配置选项
    const option = {
        tooltip: {
            trigger: 'axis',
            axisPointer: {
                type: 'cross'
            },
            formatter: function(params) {
                if (!params || params.length === 0) {
                    return '';
                }
                
                const dataIndex = params[0].dataIndex;
                if (dataIndex < 0 || dataIndex >= data.length) {
                    return '数据索引超出范围';
                }
                
                // 直接从原始数据中获取对应索引的K线数据
                const item = data[dataIndex];
                const timeStr = formatDate(new Date(item.time));
                
                // 确定是上涨还是下跌
                const isUp = item.close >= item.open;
                const colorStyle = isUp ? 'color:#14b143' : 'color:#ef232a'; // 上涨绿色，下跌红色
                
                return `
                    <div style="font-size:14px;font-weight:bold;margin-bottom:5px">
                        ${timeStr}
                    </div>
                    <div style="margin: 3px 0">
                        <span style="display:inline-block;margin-right:5px;width:10px;height:10px;background-color:${isUp ? '#14b143' : '#ef232a'}"></span>
                        <span style="font-weight:bold;">开盘价: <span style="${colorStyle}">${item.open.toFixed(2)}</span></span>
                    </div>
                    <div style="margin: 3px 0">
                        <span style="display:inline-block;margin-right:5px;width:10px;height:10px;background-color:${isUp ? '#14b143' : '#ef232a'}"></span>
                        <span style="font-weight:bold;">收盘价: <span style="${colorStyle}">${item.close.toFixed(2)}</span></span>
                    </div>
                    <div style="margin: 3px 0">
                        <span style="display:inline-block;margin-right:5px;width:10px;height:10px;background-color:${isUp ? '#14b143' : '#ef232a'}"></span>
                        最低价: ${item.low.toFixed(2)}
                    </div>
                    <div style="margin: 3px 0">
                        <span style="display:inline-block;margin-right:5px;width:10px;height:10px;background-color:${isUp ? '#14b143' : '#ef232a'}"></span>
                        最高价: ${item.high.toFixed(2)}
                    </div>
                    <div style="margin: 5px 0; padding-top:3px; border-top:1px solid #eee;">
                        <span style="${colorStyle}; font-weight:bold;">
                            ${isUp ? '↑' : '↓'} ${Math.abs(item.close - item.open).toFixed(2)} (${((Math.abs(item.close - item.open) / item.open) * 100).toFixed(2)}%)
                        </span>
                    </div>
                `;
            }
        },
        grid: {
            left: '10%',
            right: '10%',
            bottom: '15%'
        },
        xAxis: {
            type: 'category',
            data: timeData,
            scale: true,
            axisLine: { lineStyle: { color: '#8392A5' } }
        },
        yAxis: {
            scale: true,
            splitArea: {
                show: true
            }
        },
        dataZoom: [
            {
                type: 'inside',
                start: startPercent,
                end: endPercent
            },
            {
                show: true,
                type: 'slider',
                bottom: 5,
                start: startPercent,
                end: endPercent
            }
        ],
        series: [
            {
                name: '价格',
                type: 'candlestick',
                data: klineData,
                itemStyle: {
                    color: '#14b143',       // 阳线颜色（收盘价 > 开盘价）
                    color0: '#ef232a',      // 阴线颜色（收盘价 < 开盘价）
                    borderColor: '#14b143', // 阳线边框
                    borderColor0: '#ef232a' // 阴线边框
                }
            }
        ]
    };
    
    // 设置K线图选项
    myChart.setOption(option);
    
    // 自动调整大小
    window.addEventListener('resize', function() {
        if (myChart) {
            myChart.resize();
        }
    });
}

// 格式化日期
function formatDate(date) {
    return `${padZero(date.getHours())}:${padZero(date.getMinutes())}`;
}

// 数字前补零
function padZero(num) {
    return num < 10 ? '0' + num : num;
}

// 格式化日期范围
function formatDateRange(startTimestamp, endTimestamp) {
    const start = new Date(startTimestamp);
    const end = new Date(endTimestamp);
    
    return `${start.getFullYear()}-${padZero(start.getMonth() + 1)}-${padZero(start.getDate())} ${padZero(start.getHours())}:${padZero(start.getMinutes())}:${padZero(start.getSeconds())} 至 ${end.getFullYear()}-${padZero(end.getMonth() + 1)}-${padZero(end.getDate())} ${padZero(end.getHours())}:${padZero(end.getMinutes())}:${padZero(end.getSeconds())}`;
}

// 主函数：获取并分析数据
async function fetchAndAnalyzeData() {
    try {
        // 显示加载提示
        document.getElementById('loading').style.display = 'flex';
        document.getElementById('results').style.display = 'none';
        document.getElementById('klineContainer').style.display = 'none';
        
        // 获取参数
        const symbol = document.getElementById('symbol').value;
        const interval = document.getElementById('interval').value;
        const timeRange = document.getElementById('timeRange').value;
    
        // 获取时间范围
        const startTime = getStartTimestamp(timeRange);
        const endTime = getEndTimestamp(timeRange);
        
        // 确保使用小写的范围值
        const timeRangeLower = timeRange.toLowerCase();
        
        // 直接从服务器获取统计数据，使用缓存机制
        const statsResponse = await fetch(`/api/kline/stats-data?symbol=${symbol}&interval=${interval}&range=${timeRangeLower}`);
        if (!statsResponse.ok) {
            throw new Error(`获取统计数据失败: ${statsResponse.status}`);
        }
        const statsData = await statsResponse.json();
        
        // 从响应数据中提取统计信息
        const analysis = {
            total: statsData.data.total,
            upCount: statsData.data.up,
            downCount: statsData.data.down,
            flatCount: statsData.data.flat,
            upPercent: (statsData.data.up / statsData.data.total * 100).toFixed(2),
            downPercent: (statsData.data.down / statsData.data.total * 100).toFixed(2),
            flatPercent: (statsData.data.flat / statsData.data.total * 100).toFixed(2),
            continuousUpCounts: statsData.data.consecutive.up,
            continuousDownCounts: statsData.data.consecutive.down
        };
        
        console.log('服务器统计数据:', statsData);
            
        // 更新时间范围显示 - 使用服务器返回的时间范围
        if (statsData.data.timeRange && statsData.data.timeRange.start && statsData.data.timeRange.end) {
            const serverStartTime = new Date(statsData.data.timeRange.start).getTime();
            const serverEndTime = new Date(statsData.data.timeRange.end).getTime();
            console.log('使用服务器返回的时间范围:', new Date(serverStartTime).toLocaleString(), '至', new Date(serverEndTime).toLocaleString());
            document.getElementById('timeRangeInfo').textContent = formatDateRange(serverStartTime, serverEndTime);
        } else {
            // 如果服务器没有返回时间范围，则使用客户端计算的
            document.getElementById('timeRangeInfo').textContent = formatDateRange(startTime, endTime);
        }
        
        // 更新UI
        updateUI(analysis);
            
        // 如果是选择"今天"，还需要获取K线数据以显示图表
        if (timeRangeLower === 'today') {
            // 获取K线数据
            const data = await fetchKlineData(symbol, interval, startTime, endTime, timeRangeLower);
            showKlineChart(data, symbol, interval);
        }

        // 显示结果
        document.getElementById('results').style.display = 'block';
    } catch (error) {
        console.error('获取和分析数据出错:', error);
        alert('获取数据时出错: ' + error.message);
    } finally {
        // 隐藏加载提示
        document.getElementById('loading').style.display = 'none';
    }
}